package com.yanjiali.config.feign;

import com.yanjiali.constant.Constants;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Package: com.yanjiali.config.feign
 * @Author: yanjiali
 * @Created: 2025/4/18 22:15
 * TODO 远程调用拦截配置，用于传递请求头中的token
 */
public class OAuth2FeignConfig implements RequestInterceptor {

    //TODO 配置超时时间
    @Bean
    public Request.Options options() {
        return new Request.Options(
                5000,     // 连接超时时间，单位毫秒
                10000     // 读取超时时间，单位毫秒
        );
    }

    @Override
    public void apply(RequestTemplate template) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        String header = null;
        if (requestAttributes == null) {
            header = "bearer " + Constants.INSIDE_TOKEN;    //使用内置的token
        } else {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            header = request.getHeader(HttpHeaders.AUTHORIZATION);
        }

        if (!StringUtils.isEmpty(header)) {
            template.header(HttpHeaders.AUTHORIZATION, header);
        }
    }
}
